# # chat/views.py
# from django.shortcuts import render
 
# def index(request):
#     return render(request, 'chat/index.html', {})
 
# def room(request, room_name):
#     return render(request, 'chat/room.html', {
#         'room_name': room_name
#     })

from django.shortcuts import render, get_object_or_404
from goods.models import GoodsInfo  # 假设商品模型在 goods 应用中
from django.utils.text import slugify
from pypinyin import lazy_pinyin

def pinyin_slugify(value):
    pinyin_list = lazy_pinyin(value)
    pinyin_str = ''.join(pinyin_list)
    return slugify(pinyin_str)



def index(request):
    return render(request, 'chat/index.html', {})


from django.contrib.auth.decorators import login_required
# @login_required  # 确保用户已登录
# def room(request, good_id):
#     # print("######################################################################")
#     # print(good_id)
#     # print("######################################################################")
#     good = get_object_or_404(GoodsInfo, id=good_id)
#     room_name = f"{good.user.username}_{good.title}"
#     room_name = pinyin_slugify(room_name)  # 使用拼音转换后的 slugify 函数生成有效的组名room_name = slugify(room_name)  # 使用 slugify 函数生成有效的组名
#     # print("######################################################################")
#     # print(room_name)
#     # print("######################################################################")
#     context = {
#         'room_name': room_name
#     }
#     return render(request, 'chat/room.html', context)
@login_required
def room(request, room_name):
    return render(request, 'chat/room.html', {
        'room_name': room_name
    })

# goods/views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from chat.models import ChatRoom


@login_required
def create_chatroom(request, good_id):
    good = get_object_or_404(GoodsInfo, id=good_id)
    visitor = request.user
    publisher = good.user

    # 以当前访问者和商品发布者的序号为房间名称
    room_name = f"{visitor.id}_{publisher.id}_{good.id}"

    # 获取或创建聊天室
    chatroom, created = ChatRoom.objects.get_or_create(name=room_name, good=good)
    chatroom.participants.add(visitor, publisher)



    # 重定向到聊天室页面
    return redirect('chat:room', room_name=chatroom.name)
